import { defineStore } from 'pinia';
import { computed, reactive } from 'vue';
import { LoginUser } from '@/pages/Login/login_operate';
import { ApiCode, RequestLoginUser } from '@/config/api_config/api_interface';
import { adminLogin } from '@/config/api_config/apis';
import { RouteNameEnum } from '@/config/router_config/router_components';
import { router } from '@/config/router_config';
import { WindUser } from '@/global';
class UserState {
  private _token!: string | null;
  private _userInfo: WindUser | null;
  public constructor () {
    this._userInfo = null;
    this._token = null;
  }

  get token (): string | null {
    return this._token;
  }

  set token (value: string | null) {
    this._token = value;
  }

  get userInfo (): WindUser | null {
    return this._userInfo;
  }

  set userInfo (value: WindUser | null) {
    this._userInfo = value;
  }
}
/**
 * 跟User相关的状态
 */
const useUserStore = defineStore('user', () => {
  // 状态对象
  const userState = reactive<UserState>(new UserState());
  // 关于用户的getters
  const token = computed(() => userState.token);
  const userInfo = computed(() => userState.userInfo);
  // 所有的actions
  const login = async (loginUser: LoginUser) => {
    const loginAccount: RequestLoginUser = { loginAccountType: loginUser.accountType, loginAccountName: loginUser.userName, loginPassword: loginUser.password };
    const res = await adminLogin(loginAccount);
    if (res.apiCode === ApiCode.Success) {
      userState.token = res.result.token;
      userState.userInfo = res.result.userInfo;
      await router.push({ name: RouteNameEnum.homePage });
    }
  };
  const logout = async () => {
    userState.token = null;
    userState.userInfo = null;
    await router.push({ name: RouteNameEnum.login });
  };
  return {
    userState, token, userInfo, login, logout
  };
});
export default useUserStore;
